package com.caipiao.service.impl;

import com.caipiao.mapper.*;
import com.caipiao.pojo.ObjectResult;
import com.caipiao.pojo.SMobileCode;
import com.caipiao.pojo.SUser;
import com.caipiao.pojo.XMLBean;
import com.caipiao.service.UserService;

import com.caipiao.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.security.Signature;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/12/29.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{

    private static Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SMobileCodeMapper sMobileCodeMapper;
    @Autowired
    private SUserBankMapper selectByMobile;
    @Autowired
    private SIntegralMapper sIntegralMapper;


    @Override
    public ObjectResult regist(XMLBean xmlBean) {

        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser user = sUserMapper.selectByMap(map);
        if (user != null){
            return ObjectResult.build("0","该用户已注册");
        }
        if (xmlBean.getPassword().length()<6){
            return  ObjectResult.build("0 ","密码不能低于六位");
        }
        //验证码校验
        SMobileCode mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
        if(!mobileCode.getCode().equals(xmlBean.getCode())){
            return ObjectResult.build("0","验证码错误");
        }
        if(System.currentTimeMillis()-mobileCode.getSendTime()>5*60*1000){
            return ObjectResult.build("0","验证码失效");
        }

        try {
            SUser sUser = new SUser();
            if(!StringUtil.isEmpty(xmlBean.getSalt())){
                map.clear();
                map.put("salt",xmlBean.getSalt());
                sUser = sUserMapper.selectByMap(map);
                if (sUser==null){
                    return ObjectResult.build("0","邀请码错误");
                }

            }


            //md5加密
            String password = CommonUtils.getMD5(xmlBean.getPassword());
            //生成邀请码
            String random = RandomUtil.getRandom(6);


            //添加用户表
            user = new SUser();
            user.setMobile(xmlBean.getMobile());
            user.setPassword(password);
            user.setAddTime(new Date());
            user.setSalt(random);
            user.setUserId(sUser.getId());
//            user.setAccountAble(1);//新注册用户获取100积分
            sUserMapper.insertSelective(user);

            //积分记录
//            map.put("userId",user.getId());
//            map.put("integral",100);
//            map.put("type",4);
//            sIntegralMapper.insertIntegralByMap(map);


            //生成token
            String token =CommonUtils.createToken(user.getMobile(),password,user.getId(),random);

            map.clear();
            map.put("mobile",user.getMobile());
            map.put("username",user.getUsername());
            map.put("avator",user.getAvator());
            map.put("sex",user.getSex());
            map.put("token",token);
            map.put("isRealname",user.getIsRealname());
            return ObjectResult.build("1","注册成功",map);
        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionUtil.logError(e,LOG);
            return ObjectResult.build("0","注册失败");
        }
    }

    @Override
    public ObjectResult login(XMLBean xmlBean) {
        Map<String, Object> data = new HashMap<>();
        data.put("mobile",xmlBean.getMobile());
        SUser user = sUserMapper.selectByMap(data);
        String md5 = CommonUtils.getMD5(xmlBean.getPassword());

        data.clear();
        if(user == null){
            data.put("loginTypeTip","用户名或密码错误");
            return  ObjectResult.build("0","用户名或密码错误",data);
        }

        if(!md5.equals(user.getPassword())){
            data.put("loginTypeTip","用户名或密码错误");
            return  ObjectResult.build("0","用户名或密码错误",data);
        }

        //返回数据
        String token =CommonUtils.createToken(user.getMobile(),user.getPassword(),user.getId(),user.getSalt());
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",user.getMobile());
        map.put("username",user.getUsername());
        map.put("avator",user.getAvator());
        map.put("sex",user.getSex());
        map.put("token",token);
        map.put("isRealname",user.getIsRealname());
        return ObjectResult.build("1","登陆成功",map);

    }

    @Override
    public ObjectResult update(XMLBean xmlBean, HttpServletRequest request) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));

        if (!sUser.getUsername().equals(xmlBean.getUsername())){
            Map<String,Object> map = new HashMap<>();
            map.put("username",xmlBean.getUsername());
            SUser user = sUserMapper.selectByMap(map);
            if (user != null){
                return ObjectResult.build("0","该昵称已被使用");
            }
        }
        try {
            String head = request.getParameter("head");

            //修改头像
            if (!StringUtil.isEmpty(head)){
                String imageName = ImageUploadUtil.uploadBaseImg(ConfigUtils.HEAD_URL, head);
                sUser.setAvator(ConfigUtils.FILE_URL+"image/head/"+imageName);

            }

            //修改个人信息
            sUser.setSex(Integer.parseInt(xmlBean.getSex()));
            sUser.setUsername(xmlBean.getUsername());
            sUser.setMobile(xmlBean.getMobile());

            sUserMapper.updateByPrimaryKeySelective(sUser);
            return ObjectResult.build("1","修改个人信息成功");
        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionUtil.logError(e,LOG);
            return ObjectResult.build("0","修改个人信息失败，请联系客服");
        }
    }

    @Override
    public ObjectResult updatePassword(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser user = sUserMapper.selectByMap(map);
        if (user==null){
            return ObjectResult.build("0","未注册的用户");
        }
        try {
            if (xmlBean.getPassword().length()<6){
                return  ObjectResult.build("0 ","密码不能低于六位");
            }
            //md5加密
            String password = CommonUtils.getMD5(xmlBean.getPassword());
            if (user.getPassword().equals(password)){
                return  ObjectResult.build("0 ","不能与原密码相同");
            }

            //验证码校验
            SMobileCode mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
            if(!mobileCode.getCode().equals(xmlBean.getCode())){
                return ObjectResult.build("0","验证码错误");
            }
            if(System.currentTimeMillis()-mobileCode.getSendTime()>5*60*1000){
                return ObjectResult.build("0","验证码失效");
            }

            user.setPassword(password);
            sUserMapper.updateByPrimaryKeySelective(user);
            return ObjectResult.build("1","修改密码成功");
        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionUtil.logError(e,LOG);
            return ObjectResult.build("0","修改密码失败");
        }
    }

    @Override
    public ObjectResult weixinLogin(XMLBean xmlBean, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        map.put("wxId",xmlBean.getWxId());
        SUser user = sUserMapper.selectByMap(map);

        if(user == null){
//            SUser sUser = new SUser();
//            //生成邀请码
//            String random = RandomUtil.getRandom(6);
//
//            //添加用户表
//            user = new SUser();
//            //头像
//            String head = request.getParameter("head");
//
//            user.setAvator(head);
//            user.setUsername(xmlBean.getUsername());
//            user.setWxId(xmlBean.getWxId());
//            user.setSex(Integer.parseInt(xmlBean.getSex()));
//            user.setAddTime(new Date());
//            user.setSalt(random);
//            user.setUserId(sUser.getId());
//            user.setAccountAble(100);//新注册用户获取100积分
//            sUserMapper.insertSelective(user);   //积分记录
//
//
//            map.put("userId",user.getId());
//            map.put("integral",100);
//            map.put("type",4);
//            sIntegralMapper.insertIntegralByMap(map);
            map.clear();
            map.put("isWeixin",0);
            return ObjectResult.build("1","未绑定手机号",map);

        }


        //返回数据
        String token =CommonUtils.createToken(user.getMobile(),user.getPassword(),user.getId(),user.getSalt());
        map.clear();
        map.put("mobile",user.getMobile()==null? "":user.getMobile());
            map.put("username",user.getUsername()==null?"":user.getUsername());
        map.put("avator",user.getAvator());
        map.put("sex",user.getSex());
        map.put("token",token);
        map.put("isRealname",user.getIsRealname());
        map.put("isWeixin",1);
        return ObjectResult.build("1","登陆成功",map);
    }

    @Override
    public ObjectResult bindingMobile(XMLBean xmlBean,HttpServletRequest request) {

        //验证码校验
        SMobileCode mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
        if(!mobileCode.getCode().equals(xmlBean.getCode())){
            return ObjectResult.build("0","验证码错误");
        }
        if(System.currentTimeMillis()-mobileCode.getSendTime()>5*60*1000){
            return ObjectResult.build("0","验证码失效");
        }
        String head = request.getParameter("head");
        String md5 = CommonUtils.getMD5(xmlBean.getPassword());

        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser sUser = sUserMapper.selectByMap(map);
        //如果为空添加新用户，有则修改信息
        if (sUser == null) {
            //生成邀请码
            String random = RandomUtil.getRandom(6);

            //添加用户表
            sUser = new SUser();
            //头像
            sUser.setAvator(head);
            sUser.setMobile(xmlBean.getMobile());
            sUser.setPassword(md5);
            sUser.setUsername(xmlBean.getUsername());
            sUser.setWxId(xmlBean.getWxId());
            sUser.setSex(Integer.parseInt(xmlBean.getSex()));
            sUser.setAddTime(new Date());
            sUser.setSalt(random);
//            sUser.setUserId(sUser.getId());
//            sUser.setAccountAble(100);//新注册用户获取100积分
            sUserMapper.insertSelective(sUser);   //积分记录

            map.put("userId", sUser.getId());
            map.put("integral", 100);
            map.put("type", 4);
            sIntegralMapper.insertIntegralByMap(map);
        } else {
            if (!md5.equals(sUser.getPassword())) {
                Map<String, Object> data = new HashMap<>();
                data.put("loginTypeTip", "用户名或密码错误");
                return ObjectResult.build("0", "用户名或密码错误", data);
            }
            sUser.setModifyTime(new Date());
            sUser.setWxId(xmlBean.getWxId());
            sUser.setAvator(StringUtil.isEmpty(sUser.getAvator()) ? head : null);
            sUser.setUsername(StringUtil.isEmpty(sUser.getUsername()) ? xmlBean.getUsername() : null);
            sUser.setSex(Integer.parseInt(xmlBean.getSex()));

            sUserMapper.updateByPrimaryKeySelective(sUser);

        }

        //返回数据
        String token =CommonUtils.createToken(sUser.getMobile(),sUser.getPassword(),sUser.getId(),sUser.getSalt());
        map.clear();
        map.put("mobile",sUser.getMobile()==null? "":sUser.getMobile());
        map.put("username",sUser.getUsername()==null?"":sUser.getUsername());
        map.put("avator",sUser.getAvator());
        map.put("sex",sUser.getSex());
        map.put("token",token);
        map.put("isRealname",sUser.getIsRealname());

        return ObjectResult.build("1","绑定成功",map);

    }
}
